package com.ryskoo.customer.vendormanager.service;

import com.ryskoo.customer.vendormanager.domain.VendorManagerPO;
import com.ryskoo.customer.vendormanager.repository.IVendorManagerRepository;
import com.ryskoo.framework.core.bean.QueryConditionEnum;
import com.ryskoo.framework.core.bean.QueryMessageDTO;
import com.ryskoo.framework.core.exception.InvalidParamException;
import com.ryskoo.framework.core.service.BasicServiceImpl;
import com.ryskoo.framework.core.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Shawn
 */
@Service("customerVendorManagerServiceImpl")
public class VendorManagerServiceImpl extends BasicServiceImpl<VendorManagerPO> implements IVendorManagerService {
	@Autowired
	private IVendorManagerRepository managerRepository;

	@PostConstruct
	public void init() {
		this.setDao(managerRepository);
	}

	@Override
	public void create(VendorManagerPO vendorManager) {
        checkBeforeCreate(vendorManager);
        vendorManager.setPassword(MD5Util.md5(vendorManager.getLoginName() + vendorManager.getPassword()));
		super.create(vendorManager);
	}

    private void checkBeforeCreate(VendorManagerPO vendorManager) {
	    checkName(vendorManager.getName());
        checkLoginName(vendorManager, true);
        checkMobile(vendorManager, true);
        checkPassword(vendorManager.getPassword());
    }

    @Override
    public void update(VendorManagerPO vendorManager) {
	    checkBeforeUpdate(vendorManager);
        super.update(vendorManager);
    }

    private void checkBeforeUpdate(VendorManagerPO vendorManager) {
        checkName(vendorManager.getName());
        checkLoginName(vendorManager, true);
        checkMobile(vendorManager, true);
    }

    private void checkName(String name) {
        if (StringUtils.isBlank(name)) {
            throw new InvalidParamException("姓名不能为空");
        }
        if (name.length() < 2) {
            throw new InvalidParamException("姓名最少2个字符");
        }
    }

    private void checkLoginName(VendorManagerPO vendorManager, boolean isUpdate) {
	    String loginName = vendorManager.getLoginName();
        if (StringUtils.isBlank(loginName)) {
            throw new InvalidParamException("登录账号不能为空");
        }
        if (loginName.length() < 5) {
            throw new InvalidParamException("登录账号最少5个字符");
        }
        QueryMessageDTO queryMessage = new QueryMessageDTO();
        queryMessage.addCondition("loginName", QueryConditionEnum.EQ.name(), loginName);
        queryMessage.addCondition("vendorUuid", QueryConditionEnum.EQ.name(), vendorManager.getVendorUuid());
        if (isUpdate) {
            // 如果是修改信息，则把自身除外
            queryMessage.addCondition("uuid", QueryConditionEnum.NE.name(), vendorManager.getUuid());
        }
        List<VendorManagerPO> list = managerRepository.queryByCondition(queryMessage, false);
        if (null != list && !list.isEmpty()) {
            throw new InvalidParamException("登录账号已存在");
        }
    }

    private void checkMobile(VendorManagerPO vendorManager, boolean isUpdate) {
        if (StringUtils.isBlank(vendorManager.getMobile())) {
            throw new InvalidParamException("手机号不能为空");
        }
        if (!vendorManager.getMobile().matches("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$")) {
            throw new InvalidParamException("手机号格式有误");
        }
        QueryMessageDTO queryMessage = new QueryMessageDTO();
        queryMessage.addCondition("mobile", QueryConditionEnum.EQ.name(), vendorManager.getMobile());
        if (isUpdate) {
            // 如果是修改信息，则把自身除外
            queryMessage.addCondition("uuid", QueryConditionEnum.NE.name(), vendorManager.getUuid());
        }
        List<VendorManagerPO> list = managerRepository.queryByCondition(queryMessage, false);
        if (null != list && !list.isEmpty()) {
            throw new InvalidParamException("手机号已存在");
        }
    }

    private void checkPassword(String password) {
        if (StringUtils.isBlank(password)) {
            throw new InvalidParamException("登录密码不能为空");
        }
        if (password.length() < 6) {
            throw new InvalidParamException("登录密码最少6个字符");
        }
    }



    /**
	 * 根据用户名查询管理员信息
	 * 
	 * @param userName
	 * @return
	 */
	@Override
	public VendorManagerPO getManagerByLoginName(String userName) {
		return managerRepository.getManagerByLoginName(userName);
	}

	/**
	 * 根据 商户uuid和是否超级管理员， 查找对应的员工
	 * 
	 * @param vendorUuids
	 * @param superManager
	 * @return
	 */
	@Override
	public List<VendorManagerPO> getVendorManagerByVendorUuid(List<String> vendorUuids, Boolean superManager) {
		return managerRepository.getVendorManagerByVendorUuid(vendorUuids, superManager);
	}

    /**
     * 修改员工登录密码
     *
     * @param vendorManager 员工信息
     */
    @Override
    public void modifyPassword(VendorManagerPO vendorManager) {
        checkPassword(vendorManager.getPassword());
        vendorManager.setPassword(MD5Util.md5(vendorManager.getLoginName() + vendorManager.getPassword()));
        super.update(vendorManager);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletes(List<String> ids) {
        for (String id : ids) {
            VendorManagerPO vendorManager = managerRepository.getByUuid(id);
            if (vendorManager != null && vendorManager.isSuperManager()) {
                throw new InvalidParamException("商户管理员账户不允许删除");
            }
        }
        super.deletes(ids);
    }

    @Override
    public List<VendorManagerPO> getManagerByVendorUuidAndType(String vendorUuid, int type) {
        return managerRepository.getManagerByVendorUuidAndType(vendorUuid,type);
    }

    @Override
    public void changeState(String employeeUuid, boolean state) {
        VendorManagerPO po = managerRepository.getByUuid(employeeUuid);
        po.setState(state);
        managerRepository.update(po);
    }

    @Override
    public void createVendorManager(VendorManagerPO vendorManagerPO) {
        // 如果 receiveNotification 是true,则需要将该商户其他的员工的该属性置为false
        if(vendorManagerPO.isReceiveNotification()){
            managerRepository.setNotReceiveNotificationToAll(vendorManagerPO.getVendorUuid(),vendorManagerPO.getEmployeeType(),"");
        }
        managerRepository.create(vendorManagerPO);
    }

    @Override
    public void updateVendorManager(VendorManagerPO vendorManagerPO) {
        // 如果 receiveNotification 是true,则需要将该商户其他的员工的该属性置为false
        if(vendorManagerPO.isReceiveNotification()){
            managerRepository.setNotReceiveNotificationToAll(vendorManagerPO.getVendorUuid(),vendorManagerPO.getEmployeeType(),vendorManagerPO.getUuid());
        }
        managerRepository.update(vendorManagerPO);
    }
}
